package edu.gyc.okshiro.controller;


import edu.gyc.okshiro.model.Myuser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ls
 * @since 2021-01-03
 */
@Controller
@Slf4j
public class MyuserController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) {
        log.info("called login");
        String exception = (String) request.getAttribute("shiroLoginFailure");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String msg = null;
        if (exception!=null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                msg = "账号不存在";
            }else if (IncorrectCredentialsException.class.getName().equals(exception)) {

                msg = "密码不正确";
            }

        }
        model.addAttribute("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "/login";

    }
    @RequestMapping("/logout")
    public String logout() {

        Subject currentUserSubject = SecurityUtils.getSubject();
        log.info((String)currentUserSubject.getPrincipal()+"退出系统.");
        currentUserSubject.logout();


        return "/";
    }
}

